/**
 * Copyright (c) 2012 Axa Holding Belgium, SA. All rights reserved.
 * This software is the confidential and proprietary information of the AXA Group.
 */
package chabernac.android.draw;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;

public class AnimationView extends View {
  public static final long DELAY = 1000 / 30;
  private SingleObjectQueue<AbstractDrawable> myQueue = new SingleObjectQueue<AbstractDrawable>();
  private ScheduledExecutorService myExecutorService = null;
  private AbstractDrawable myCurrentDrawable = null;
  private ScheduledFuture myScheduledTask = null;
  private float offsetX = 0;
  private float offsetY = 0;

  public AnimationView( Context aContext, AttributeSet aAttrs, int aDefStyle ) {
    super( aContext, aAttrs, aDefStyle );
  }

  public AnimationView( Context aContext, AttributeSet aAttrs ) {
    super( aContext, aAttrs );
  }

  public AnimationView( Context aContext ) {
    super( aContext );
  }

  public void start(){
    if(myScheduledTask == null || myScheduledTask.isCancelled()){
    	PriorityThreadFactoryDecorator theThreadFactory = new PriorityThreadFactoryDecorator(Executors.defaultThreadFactory());
    	theThreadFactory.setPriority(Thread.NORM_PRIORITY);
    	myExecutorService =  Executors.newScheduledThreadPool( 1, theThreadFactory );
      myScheduledTask = myExecutorService.scheduleAtFixedRate( new Runnable(){
        public void run(){
          AbstractDrawable theDrawable = myQueue.get();
          if(theDrawable != null){
            myCurrentDrawable = theDrawable;
            postInvalidate();
          }
        }
      }, DELAY, DELAY, TimeUnit.MILLISECONDS);
    }
  }

  public void stop(){
    myScheduledTask.cancel( false );
  }

  public void onDraw(Canvas aCanvas){
  	aCanvas.translate(offsetX, offsetY);
    if(myCurrentDrawable != null){
      myCurrentDrawable.paint( aCanvas, this );
    }
  }

  public SingleObjectQueue<AbstractDrawable> getDrawableQueue(){
    return myQueue;
  }

	public void setTranslation(float difx, float dify) {
	 offsetX += difx;
	 offsetY += dify;
	}

}
